package com.yanqu.road.server.manager.pawnshop;

import com.yanqu.road.dao.impl.activity.pawnshop.CrossPawnshopTriggerDaoImpl;
import com.yanqu.road.dao.impl.activity.pawnshop.CrossPawnshopTriggerUserDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.pawnshop.CrossPawnshopTriggerData;
import com.yanqu.road.entity.activity.pawnshop.GlobalPawnshopData;
import com.yanqu.road.entity.activity.pawnshop.PawnshopConfig;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.logic.bussiness.activity.PawnshopBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.cross.CrossActivityRankListModel;
import com.yanqu.road.pb.activity.PawnshopProto;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityRankMgr;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossPawnshopMgr extends TempMgr {

    private static Map<Integer, GlobalPawnshopData> globalPawnshopDataMap;

    private static Map<Integer, PawnshopConfig> configMap;

    private static final Object LOCK_OBJECT = new Object();

    /**
     * zen
     *
     * @param power
     */
    public static void addGlobalPower(int activityId, int power) {
        synchronized (LOCK_OBJECT) {
            GlobalPawnshopData globalPawnshopData = getCurDayPawnshopData(activityId);
            if (!DateHelper.isSameDay(globalPawnshopData.getDayTime()/1000, System.currentTimeMillis()/1000)) {
                globalPawnshopData.setDayPower(0);
                globalPawnshopData.setDayMarkTimes(0);
                globalPawnshopData.setDayTime(System.currentTimeMillis());
            }
            globalPawnshopData.setDayPower(globalPawnshopData.getDayPower() + power);
            if (!canTrigger(globalPawnshopData)) {
                return;
            }
            Map<Integer, CrossActivityRankListModel> modelMap = ActivityRankMgr.getCrossActivityNewRankListModelMap(activityId);
            CrossActivityRankListModel model = modelMap.get(eGamePlayerEventType.PawnshopScoreCrossRank.getValue());
            List<Long> userList = new ArrayList<>();
            List<Integer> weightList = new ArrayList<>();
            PawnshopConfig config = configMap.get(activityId);
            for (CrossUserRank rank : model.getRankList()) {
                userList.add(rank.getUserId());
                long vipExp = rank.getUserBaseInfo().getVipExp();
                int vipLv = VipMgr.getVipLv(vipExp);
                List<Integer> weightParamList = config.triggerVipWeightParamList;
                int weight = 0;
                if (vipLv >= weightParamList.size()) {
                    weight = weightParamList.get(weightParamList.size() - 1);
                }else {
                    weight = weightParamList.get(vipLv);
                }
                weightList.add(weight);
            }
            int markNum = config.getMarkNum();
            for (int i = 0; i < markNum; i++) {
                int index = RandomHelper.getRandomIndexByWeight(weightList);
                Long userId = userList.get(index);
                CrossPawnshopTriggerData data = new CrossPawnshopTriggerData();
                data.setActivityId(activityId);
                data.setId(globalPawnshopData.getTriggerDataList().size() + 1);
                data.setUserId(userId);
                data.setTriggerTime(System.currentTimeMillis());
                data.setInsertOption();
                globalPawnshopData.addTriggerData(data);
            }
            globalPawnshopData.setDayMarkTimes(globalPawnshopData.getDayMarkTimes() + 1);
            //同步到游戏服
            syncTriggerData(activityId,globalPawnshopData);
        }

    }

    private static void syncTriggerData(int activityId,GlobalPawnshopData globalPawnshopData) {
        List<CrossPawnshopTriggerData> triggerDataList = globalPawnshopData.getTriggerDataList();
        if (triggerDataList.isEmpty()) {
            return;
        }
        PawnshopProto.PawnshopSyncTriggerMsg.Builder msg = PawnshopProto.PawnshopSyncTriggerMsg.newBuilder();
        for (CrossPawnshopTriggerData data : triggerDataList) {
            PawnshopProto.PawnshopTriggerDataMsg.Builder builder = PawnshopProto.PawnshopTriggerDataMsg.newBuilder();
            builder.setId(data.getId());
            builder.setTriggerTime(data.getTriggerTime());
            builder.setUserId(data.getUserId());
            msg.addData(builder);
        }
        msg.setActivityId(activityId);
        YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_PAWNSHOP_SYNC_CROSS_TRIGGER, msg);
        PawnshopConfig config = configMap.get(activityId);
        List<Long> serverIdList = config.getActivityInfo().getServerIdList();
        for (Long serverId : serverIdList) {
            MessageHelper.sendPacket(serverId, -1, message);
        }
    }

    private static boolean canTrigger(GlobalPawnshopData globalPawnshopData) {
        int activityId = globalPawnshopData.getActivityId();
        PawnshopConfig config = configMap.get(activityId);
        if (config == null) {
            ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
            if (activityInfo == null) {
                return false;
            }
            loadNewActivityInfo(activityInfo);
            config = configMap.get(activityId);
            if (config == null) {
                return false;
            }
        }
        return config.canTrigger(globalPawnshopData.getDayPower(), globalPawnshopData.getDayMarkTimes());
    }

    private static GlobalPawnshopData getCurDayPawnshopData(int activityId) {
        GlobalPawnshopData data = globalPawnshopDataMap.get(activityId);
        long todayZeroTimeStamp = DateHelper.getTodayZeroTimeStamp();
        if (data == null) {
            synchronized (globalPawnshopDataMap) {
                data = globalPawnshopDataMap.get(activityId);
                if (data == null) {
                     data = new GlobalPawnshopData();
                    data.setActivityId(activityId);
                    data.setDayPower(0);
                    data.setDayTime(todayZeroTimeStamp);
                    data.setTriggerDataList(new ArrayList<>());
                    data.setInsertOption();
                    globalPawnshopDataMap.put(activityId, data);
                }
            }
        }
        return data;
    }

    @Override
    public boolean reloadData() throws Exception {
        configMap = new ConcurrentHashMap<>();
        globalPawnshopDataMap = new ConcurrentHashMap<>();
        // 获取进行中的活动信息
        String nowTimeStr = DateHelper.getCurrentDateTimeString();
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(eActivityType.PawnshopActivity.getValue());
        Map<Integer, ActivityInfo> tempActivityInfoMap = ActivityBussiness.getOpenCrossRankActivityInfoMapByCrossServerId(activityTypeList, nowTimeStr, CrossBaseServer.getInstance().getServerId());
        for (ActivityInfo activityInfo : tempActivityInfoMap.values()) {
            loadNewActivityInfo(activityInfo);
            GlobalPawnshopData globalPawnshopData = new CrossPawnshopTriggerDaoImpl().getGlobalPawnshopData(activityInfo.getActivityId());
            if (globalPawnshopData != null) {
                List<CrossPawnshopTriggerData> list = new CrossPawnshopTriggerUserDaoImpl().getCrossPawnshopTriggerData(activityInfo.getActivityId());
                globalPawnshopData.setTriggerDataList(list);
                globalPawnshopDataMap.put(activityInfo.getActivityId(), globalPawnshopData);
            }
        }
        return true;
    }

    private static void loadNewActivityInfo(ActivityInfo activityInfo) {
        PawnshopConfig tmpConfig = new PawnshopConfig();
        tmpConfig.setActivityInfo(activityInfo);
        // 感觉活动ID获取配置
        int activityId = tmpConfig.getActivityId();
        tmpConfig.setConfPawnshopList(PawnshopBussiness.getConfPawnshopList(activityId));
        tmpConfig.setConfPawnshopStaffList(PawnshopBussiness.getConfPawnshopStaffList(activityId));
        tmpConfig.setConfPawnshopItemList(PawnshopBussiness.getConfPawnshopItemList(activityId));
        tmpConfig.setConfPawnshopItemLvList(PawnshopBussiness.getConfPawnshopItemLvList(activityId));
        tmpConfig.setConfPawnshopEventMap(PawnshopBussiness.getConfPawnshopEventMap(activityId));

        // 解析当铺的参数配置
        Map<Integer, Map<String, ActivityConfig>> activityConfigMap = ActivityBussiness.getActivityConfigMap(Collections.singletonList(activityId));
        tmpConfig.parseParam(activityConfigMap.get(activityId));
        configMap.put(activityId, tmpConfig);
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        if (globalPawnshopDataMap != null) {
            for (GlobalPawnshopData data : new ArrayList<>(globalPawnshopDataMap.values())) {
                if (data.isInsertOption()) {
                    new CrossPawnshopTriggerDaoImpl().add(data);
                } else if (data.isUpdateOption()) {
                    new CrossPawnshopTriggerDaoImpl().update(data);
                }
                for (CrossPawnshopTriggerData triggerData : data.getTriggerDataList()) {
                    if (triggerData.isInsertOption()) {
                        new CrossPawnshopTriggerUserDaoImpl().add(triggerData);
                    }
                }
            }
        }
        return true;
    }
}
